package com.winhxd.b2c.message.sms;

import com.winhxd.b2c.common.domain.message.condition.SMSCondition;
import com.winhxd.b2c.common.domain.message.model.MessageSmsHistory;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.message.dao.MessageSmsHistoryMapper;
import com.winhxd.b2c.message.sms.model.SmsReturn;
import com.winhxd.b2c.message.sms.enums.SmsReturnStatusEnum;
import com.winhxd.b2c.message.sms.enums.SmsSendStatusEnum;
import com.winhxd.b2c.message.sms.enums.SmsSupplierTypeEnum;
import com.winhxd.b2c.message.sms.process.BwSmsProcess;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: SmsServerSendUtils
 * @Description: 发送短信工具类
 * @Author fanzhanzhan
 * @Date 2018-08-20 10:43
 **/
@Component
public class SmsServerSendUtils {

	private static Logger logger = LoggerFactory.getLogger(SmsServerSendUtils.class);


	@Autowired
	private MessageSmsHistoryMapper messageSmsHistoryMapper;

	/**
	 * 调用服务发送短信
	 *
	 * @param smsCondition 包含手机号、短信内容、类型、用户名、平台等信息
	 */
	public void sendSmsByCondition(SMSCondition smsCondition) {
		String type = "1";
		SmsSupplierTypeEnum typeEnum =  SmsSupplierTypeEnum.getEnumByType(type);
		smsCondition.setType(type);
		if (StringUtils.isBlank(smsCondition.getTelePhoneNo())) {
			smsCondition.setTelePhoneNo(smsCondition.getMobile());
		}
		List<MessageSmsHistory> list = new ArrayList<>();
		MessageSmsHistory tSmsSendHistory = new MessageSmsHistory();
		tSmsSendHistory.setSendType(Short.parseShort(type));
		tSmsSendHistory.setSupplyId(type);
		tSmsSendHistory.setContent(smsCondition.getContent());
		tSmsSendHistory.setSendTime(new Date());
		tSmsSendHistory.setTelephone(smsCondition.getTelePhoneNo());
		SmsReturn result = BwSmsProcess.send(smsCondition.getTelePhoneNo(),smsCondition.getContent(),Integer.valueOf(type),smsCondition.getGrp());
		logger.info("短信发送返回结果:{}",JsonUtil.toJSONString(result));
		//发送失败
		if(result==null||!result.getStatus().getStatusCode().equals(SmsReturnStatusEnum.SUCCESS.getStatusCode())){
			tSmsSendHistory.setSendStatus((short) SmsSendStatusEnum.FAIL.getCode());
			tSmsSendHistory.setErrorCode(Short.parseShort(result.getStatus().getStatusCode()));
			logger.info("["+typeEnum.getName()+"]发送失败："+ JsonUtil.toJSONString(result));
		}else{
			tSmsSendHistory.setSendStatus((short) SmsSendStatusEnum.SUCCESS.getCode());
			tSmsSendHistory.setErrorCode((short) SmsSendStatusEnum.SUCCESS.getCode());
		}
		tSmsSendHistory.setGrp(smsCondition.getGrp());
		list.add(tSmsSendHistory);
		/**
		 * 保存到数据库中
		 */
		messageSmsHistoryMapper.insertBatch(list);
	}

}
